package com.device.controller;

import com.device.dto.DeviceDTO;
import com.device.entity.Device;
import com.device.service.ConfigService;
import com.device.service.DeviceService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Optional;
import java.util.UUID;

/**
 * 设备管理
 */
@RestController
@RequestMapping("/api/devices")
@CrossOrigin(origins = "*")
@Api(tags = "设备管理")
public class DeviceController {
    
    @Autowired
    private DeviceService deviceService;

    @Autowired
    private ConfigService configService;

    private static final Logger log = LoggerFactory.getLogger(DeviceController.class);

    @ApiOperation(value = "获取所有设备", notes = "获取当前用户的所有设备列表")
    @GetMapping()
    public ResponseEntity<List<Device>> getAllDevices() {
        List<Device> devices = deviceService.getAllDevices(getUsername());
        return ResponseEntity.ok(devices);
    }

    @ApiOperation(value = "获取所有设备（包含子设备）", notes = "获取当前用户的所有设备列表，包含子设备信息")
    @GetMapping("/with-sub-devices")
    public ResponseEntity<List<DeviceDTO>> getAllDevicesWithSubDevices() {
        String username = getUsername();
        log.info("获取设备列表，用户: {}", username);
        
        // 不再使用用户名过滤，直接获取所有设备
        List<DeviceDTO> devices = deviceService.getAllDevicesWithSubDevicesNoFilter();
        log.info("查询到设备数量: {}", devices.size());
        
        return ResponseEntity.ok(devices);
    }

    @ApiOperation(value = "获取指定设备", notes = "根据设备ID获取设备详情")
    @GetMapping("/{id}")
    public ResponseEntity<Device> getDeviceById(
            @ApiParam(value = "设备ID", required = true) @PathVariable UUID id) {
        return deviceService.getDeviceById(id)
                .map(ResponseEntity::ok)
                .orElse(ResponseEntity.notFound().build());
    }

    @ApiOperation(value = "获取指定设备（包含子设备）", notes = "根据设备ID获取设备详情，包含子设备信息")
    @GetMapping("/{id}/with-sub-devices")
    public ResponseEntity<DeviceDTO> getDeviceWithSubDevicesById(
            @ApiParam(value = "设备ID", required = true) @PathVariable UUID id) {
        return deviceService.getDeviceDTOById(id)
                .map(ResponseEntity::ok)
                .orElse(ResponseEntity.notFound().build());
    }

    @ApiOperation(value = "创建设备", notes = "创建新设备")
    @PostMapping
    public ResponseEntity<Device> createDevice(
            @ApiParam(value = "设备信息", required = true) @RequestBody Device device) {
        Device createdDevice = deviceService.createDevice(device);
        return ResponseEntity.ok(createdDevice);
    }

    @ApiOperation(value = "更新设备", notes = "根据设备ID更新设备信息")
    @PutMapping("/{id}")
    public ResponseEntity<Device> updateDevice(
            @ApiParam(value = "设备ID", required = true) @PathVariable UUID id, 
            @ApiParam(value = "设备信息", required = true) @RequestBody Device device) {
        device.setId(id);
        Device updatedDevice = deviceService.updateDevice(device);
        return ResponseEntity.ok(updatedDevice);
    }

    @ApiOperation(value = "删除设备", notes = "根据设备ID删除设备及其相关配置")
    @DeleteMapping("/{id}")
    public ResponseEntity<?> deleteDevice(
            @ApiParam(value = "设备ID", required = true) @PathVariable UUID id) {
        Optional<Device> device = deviceService.getDeviceById(id);
        String deviceImei = device.orElse(new Device()).getDeviceImei();
        deviceService.deleteDevice(id);
        configService.deleteNetworkConfig(deviceImei);
        configService.deletePollingConfig(deviceImei);
        configService.deleteSerialPortConfig(deviceImei);
        return ResponseEntity.ok().build();
    }

    @ApiOperation(value = "检查IMEI是否存在", notes = "检查指定IMEI是否已存在")
    @GetMapping("/check-imei/{imei}")
    public ResponseEntity<Boolean> checkImeiExists(
            @ApiParam(value = "设备IMEI", required = true) @PathVariable String imei) {
        boolean exists = deviceService.existsByImei(imei);
        return ResponseEntity.ok(exists);
    }
    
    @ApiOperation(value = "根据IMEI查询设备", notes = "根据设备IMEI查询设备详情")
    @GetMapping("/by-imei/{imei}")
    public ResponseEntity<Device> getDeviceByImei(
            @ApiParam(value = "设备IMEI", required = true) @PathVariable String imei) {
        return deviceService.getDeviceByImei(imei)
                .map(ResponseEntity::ok)
                .orElse(ResponseEntity.notFound().build());
    }
    
    @ApiOperation(value = "根据IMEI查询设备（包含子设备）", notes = "根据设备IMEI查询设备详情，包含子设备信息")
    @GetMapping("/by-imei/{imei}/with-sub-devices")
    public ResponseEntity<DeviceDTO> getDeviceWithSubDevicesByImei(
            @ApiParam(value = "设备IMEI", required = true) @PathVariable String imei) {
        return deviceService.getDeviceByImei(imei)
                .map(device -> deviceService.getDeviceDTOById(device.getId()))
                .flatMap(dto -> dto)
                .map(ResponseEntity::ok)
                .orElse(ResponseEntity.notFound().build());
    }

    private String getUsername() {
        // 1. 获取当前认证对象
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();

        if (authentication == null) {
            return "未登录";
        }
        // 2. 获取认证主体（用户信息）
        Object principal = authentication.getPrincipal();

        // 3. 提取用户名
        String username;
        if (principal instanceof UserDetails) {
            // 若主体是UserDetails（Spring Security默认实现），直接获取username
            username = ((UserDetails) principal).getUsername();
        } else if (principal instanceof String) {
            // 少数情况主体可能是字符串（如匿名用户）
            username = principal.toString();
        } else {
            // 自定义用户对象（如实现了UserDetails的自定义类）
            username = principal.toString(); // 或根据自定义类的getter获取，如((CustomUser) principal).getUsername()
        }
        return username;
    }
} 